package com.zhl.study.service;


import com.zhl.study.module.Request;
import com.zhl.study.module.ServiceDescriptor;
import com.zhl.study.module.ServiceInstance;
import com.zhl.study.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description 管理rpc暴露的服务
 * @Author: z156940l@outlook.com
 * @className ServiceManager
 * @Date: 2024/5/20 10:28
 */
@Slf4j
public class ServiceManager {
    private Map<ServiceDescriptor, ServiceInstance> services;

    public ServiceManager(){
        this.services = new ConcurrentHashMap<>();
    }

    //注册服务
    public <T> void register(Class<T> interfaceClass,T bean){
        Method[] methods= ReflectionUtils.getPublicMethods(interfaceClass);
        for(Method method: methods){
            ServiceInstance sis = new ServiceInstance(bean,method);
            ServiceDescriptor sdp = ServiceDescriptor.from(interfaceClass,method);
            services.put(sdp,sis);
            log.info("register service: {} {}",sdp.getClazz(),sdp.getMethod());
        }
    }

    /**
     * 查找服务
     * @param request
     * @return
     */
    public ServiceInstance lookup(Request request){
        ServiceDescriptor sdp = request.getService();
        return services.get(sdp);
    }
}
